<?php

namespace support\spark;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use support\Model;
use support\spark\exception\BusinessException;

class BaseModel extends Model
{
//    /**
//     * @var string
//     */
//    protected $connection = 'mysql';

    /**
     * 格式化日期
     *
     * @param DateTimeInterface $date
     * @return string
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 根据id获取信息
     * @param $id
     * @param string $field
     * @return array
     */
    public function getInfoById($id, $field = ['*'])
    {
        $primary_key = $this->getKeyName();
        if (!$primary_key) {
            throw new BusinessException('该表无主键，不支持删除');
        }
        return $this->getInfoByWhere([$primary_key => $id], $field);

    }

    /**
     * 根据查询条件获取信息
     * @param array $where
     * @param array $field
     * @return array
     */
    public function getInfoByWhere($where, $field = ['*'])
    {
        $info = $this->doSelect($where, $field)->first();
        return $info ? $info->toArray() : [];
    }

    /**
     * 检测数据唯一
     * @param $where
     * @param int $id
     * @param string $pk
     * @return array
     */
    public function checkUnique($where, $id = 0)
    {


        if (empty($id)) {
            $has = $this->doSelect($where)->first();
        } else {
            $pk = $this->getKeyName();
            $has = $this->doSelect($where)->where([$pk, '<>', $id])->first();
        }
        return $has ? $has->toArray() : [];
    }

    /**
     * 添加单条数据
     * @param $param
     * @return array
     */
    public function insertOne($param)
    {

        return $this->query()->insertGetId($param);
    }

    /**
     * 添加单条数据
     * @param $param
     * @return array
     */
    public function insertBatch($param)
    {

        return $this->query()->insert($param);
    }


    /**
     * 根据id更新数据
     * @param $param
     * @param $id
     * @param string $pk
     * @return array
     */
    public function updateById($param, $id)
    {
        $pk = $this->getKeyName();
        //添加更新时间
        if (!isset($param['update_time'])) {
            $param['update_time'] = now();
        }
        return $this->query()->where($pk, $id)->update($param);
    }

    /**
     * 根据条件
     * @param array $param
     * @param array $id
     * @param string $pk
     * @return array
     */
    public function updateByWhere(array $param, array $where)
    {
        //添加更新时间
        if (!isset($param['update_time'])) {
            $param['update_time'] = now();
        }
        return $this->doSelect($where)->update($param);
    }

    /**
     * 根据id更新数据
     * @param array $param
     * @param array $ids
     * @return array
     */
    public function updateByIds(array $param, array $ids)
    {
        $pk = $this->getKeyName();
        //添加更新时间
        if (!isset($param['update_time'])) {
            $param['update_time'] = now();
        }
        return $this->query()->whereIn($pk, $ids)->update($param);
    }

    /**
     * 根据id删除
     * @param $id
     * @param string $pk
     * @return array
     */
    public function delById($id)
    {
        $pk = $this->getKeyName();
        return $this->query()->where($pk, $id)->delete();

    }

    /**
     * 根据id删除
     * @param array $ids
     * @return array
     */
    public function delByIds(array $ids)
    {
        $pk = $this->getKeyName();
        return $this->query()->whereIn($pk, $ids)->delete();

    }

    /**
     * 根据条件删除
     * @param array $where
     * @return boolean
     */
    public function delByWhere(array $where)
    {
        //添加更新时间
        if (!isset($param['update_time'])) {
            $param['update_time'] = now();
        }
        return $this->doSelect($where)->delete();
    }

    /**
     * 分页查询
     * @param $where
     * @param $field
     * @param $order
     * @return void
     */
    public function getPaginateList(array $where, array $field = ['*'], array $order = [], array $with = [], $limit = 10, $page = 'page')
    {
        $paginate = $this->doSelect($where, $field, $order);
        if ($with) {
            $paginate = $paginate->with($with);
        }
        return $this->setPaginate($paginate->paginate($limit));
    }


    public function getAllList(array $where, array $field = ['*'], array $order = [], array $with = [])
    {
        $list = $this->doSelect($where, $field, $order);
        if ($list) {
            $list = $list->with($with);
        }
        $list = $list->get();
        return $list ? $list->toArray() : [];
    }

    /**
     * 获取指定条目的数据
     * @param array $where
     * @param int $limit
     * @param string $field
     * @param string $order
     * @return array
     */
    public function getLimitList(array $where = [], array $field = ['*'], array $order = [], array $with = [], int $limit = 10)
    {

        $list = $this->doSelect($where, $field, $order);
        if ($list) {
            $list = $list->with($with);
        }
        $list = $list->limit($limit)->get();
        return $list ? $list->toArray() : [];
    }


    /**
     * 执行查询
     * @param array $where
     * @param string|null $field
     * @param string $order
     * @return EloquentBuilder|QueryBuilder|Model
     */
    protected function doSelect(array $where, array $field = ['*'], array $order = [])
    {
        $model = $this->query()->select($field);
        if ($where) {
            foreach ($where as $column => $value) {
                if (!is_array($value)) {
                    $model->where($column, $value);
                } else {
                    if (in_array($value[1], ['>', '=', '<', '<>', 'like', 'not like', '>=', '<='])) {
                        $model = $model->where($value[0], $value[1], $value[2]);
                    } elseif ($value[1] == 'in') {
                        $model = $model->whereIn($value[0], is_array($value[2])?$value[2]:[$value[2]] );
                    } elseif ($value[1] == 'not in') {
                        $model = $model->whereNotIn($value[0], is_array($value[2])?$value[2]:[$value[2]]);
                    } elseif ($value[1] == 'null') {
                        $model = $model->whereNull($value[0], $value[2]);
                    } elseif ($value[1] == 'not null') {
                        $model = $model->whereNotNull($value[0], $value[2]);
                    } else if ($value[1] == 'between') {
                        $model = $model->whereBetween($value[0], $value[2]);
                    } else {
                        $model = $model->whereBetween($column, $value);
                    }
                }
            }
        }
        if ($order) {
            foreach ($order as $ocolumn => $ovalue) {
                $model = $model->orderBy($ocolumn, $ovalue);
            }
        }
        return $model;
    }


    /**
     * 设置数据库分页
     * @param  $paginate
     * @return array
     */
    protected function setPaginate($paginate): array
    {
        return [
            'data' => toArray($paginate->items()),
            'total' => $paginate->total(),
        ];
    }

}